<template>
  <header class="app-header">
    <div class="header-left">
      <i class="logo"></i>
      <p>RAIM ADS-B预测系统</p>
    </div>
    <div class="header-right">
      <div class="leftMenu">
        <div
          v-for="(item, index) in homeMenuList"
          :key="index"
          @click="handleMenuClick(index)"
          :class="['topMenu', currMenuIndex === index ? 'currMenuIndex' : '']"
        >
          {{ item.name }}
        </div>
      </div>
      <div class="centerUser">
        <div
          class="user-dropdown"
          ref="dropdownRef"
          v-click-outside="closeDropdown"
        >
          <el-dropdown
            class="user-dropdown-container"
            :visible="isDropdownVisible"
            @visible-change="handleVisibleChange"
            trigger="click"
          >
            <span class="dropdown-trigger">
              <el-avatar :src="userAvatar" class="avatar" />
              <span class="username">{{ username }}</span>
              <el-badge v-if="unReadBoolean" is-dot class="unread-dot" />
              <span class="custom-arrow" :class="{ rotate: isDropdownVisible }">
                <svg
                  width="14"
                  height="8"
                  viewBox="0 0 14 8"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M1 1L7 7L13 1"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </span>
            </span>
            <template #dropdown>
              <el-dropdown-menu class="custom-dropdown-menu">
                <el-dropdown-item @click="toNotice" class="custom-item">
                  {{ t("common.notice") }}
                  <el-badge
                    v-if="noticeCount"
                    :value="noticeCount"
                    class="notice-badge"
                  />
                </el-dropdown-item>
                <el-dropdown-item @click="toPush" class="custom-item">
                  {{ t("common.predictPush") }}
                </el-dropdown-item>
                <el-dropdown-item @click="toPersonInfo" class="custom-item">
                  {{ t("common.personalInfo") }}
                </el-dropdown-item>
                <el-dropdown-item @click="toLogout" class="custom-item">
                  {{ t("common.logout") }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <div class="rightLang">
        <div
          v-for="(item, index) in langList"
          :key="index"
          @click="switchLanguage(index)"
          :class="['langList', currLangIndex === index ? 'currLangIndex' : '']"
        >
          {{ item.name }}
        </div>
      </div>
    </div>
  </header>

  <main class="app-main">
    <el-config-provider :locale="elLocale">
      <router-view />
    </el-config-provider>
  </main>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useEventStore } from "@/store";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import isValidValue from "@/utils/tools/isValidValue";
import { ElConfigProvider } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import en from "element-plus/es/locale/lang/en";
import { ClickOutside as vClickOutside } from "element-plus";
import { noticesListLimitCountApi } from "@/api/user";
import { systemUsersMeApi } from "@/api/user";
import { useUserStore } from "@/store/modules/user";
import {
  ElBadge,
  ElAvatar,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
} from "element-plus";
import localAvatar from "@/assets/images/user/user.png";

const eventStore = useEventStore();
const { t, locale } = useI18n();
const homeMenuList = computed(() => [
  { name: t("common.home"), path: "/mainLayout/home" },
  { name: t("common.raimPredict"), path: "/mainLayout/raim" },
  { name: t("common.adsbPredict"), path: "/mainLayout/ads" },
  { name: t("common.customPredict"), path: "/mainLayout/custom" },
]);
const currMenuIndex = ref(0);

const username = ref(t("common.defaultUsername"));
const userAvatar = ref(localAvatar);
const unReadBoolean = ref(false);
const noticeCount = ref(0);
const isDropdownVisible = ref(false);
const dropdownRef = ref(null);

const langList = ref([
  { name: "中", lang: "zh-cn" },
  { name: "EN", lang: "en" },
]);
const currLangIndex = ref(0);
const elLocale = computed(() => {
  return currLangIndex.value === 0 ? zhCn : en;
});

const switchLanguage = (index) => {
  const selectedLang = langList.value[index]["lang"];
  currLangIndex.value = index;
  locale.value = selectedLang;
  localStorage.setItem("language", selectedLang);
};

const userStore = useUserStore();
const router = useRouter();

const toPush = () => {
  currMenuIndex.value = "";
  router.push("/mainLayout/push");
};

const toNotice = () => {
  currMenuIndex.value = "";
  router.push("/mainLayout/notice");
};

const getNoticesListLimit = async () => {
  const { code, data } = await noticesListLimitCountApi();
  if (code === 200) {
    if (isValidValue(data)) {
      unReadBoolean.value = true;
      noticeCount.value = data;
    }
  }
};

const toPersonInfo = () => {
  currMenuIndex.value = "";
  router.push("/mainLayout/personinfo");
};

const toLogout = () => {
  userStore
    .logout()
    .then((res) => {
      if (res.code && res.code === 200) {
        router.push("/login");
      }
    })
    .catch((error) => {
      console.error("登录接口报错详情：", error);
    });
};

const handleMenuClick = (index) => {
  currMenuIndex.value = index;
  const currentPath = homeMenuList.value[index].path;
  router.push(currentPath);
};

const closeDropdown = () => {
  isDropdownVisible.value = false;
};

const handleVisibleChange = (visible) => {
  isDropdownVisible.value = visible;
};

const getSystemUsersMe = async () => {
  const { code, data } = await systemUsersMeApi();
  if (code === 200) {
    username.value = data.userName || t("common.defaultUsername");
  }
};

onMounted(() => {
  const savedLang = localStorage.getItem("language");
  if (savedLang) {
    const langIndex = langList.value.findIndex(
      (item) => item.lang === savedLang
    );
    if (langIndex !== -1) {
      currLangIndex.value = langIndex;
      locale.value = savedLang;
    }
  }
  getNoticesListLimit();
  getSystemUsersMe();
});

watch(
  () => router.currentRoute.value.path,
  (currentPath) => {
    const matchIndex = homeMenuList.value.findIndex(
      (item) => item.path === currentPath
    );
    currMenuIndex.value = matchIndex !== -1 ? matchIndex : "";
  },
  { immediate: true }
);

watch(
  () => eventStore.eventData,
  (newData) => {
    if (newData) {
      console.log("子组件通过 Pinia 传递的数据：", newData);
      getNoticesListLimit();
      eventStore.eventData = null;
    }
  },
  { immediate: false }
);
</script>

<style scoped lang="scss">
.app-header {
  width: 100%;
  height: 66px;
  .header-left {
    float: left;
    width: calc(100vw - 720px);
    height: 66px;
    background-image: url("../../assets/images/home/topLeft.png");
    background-repeat: no-repeat;
    background-size: 90% 100%;
    background-position: left;
    .logo {
      float: left;
      margin: 12px 0 0 12px;
      width: 52px;
      height: 42px;
      background-image: url("../../assets/logo.png");
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center;
    }
    p {
      float: left;
      margin-left: 12px;
      color: #fff;
      text-align: justify;
      font-size: 24px;
      font-style: normal;
      font-weight: 700;
      line-height: 66px;
    }
  }
  .header-right {
    float: right;
    margin-top: 4px;
    margin-right: 4px;
    width: 699px;
    height: 60px;
    background-image: url("../../assets/images/home/topRight.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    .leftMenu {
      float: left;
      .topMenu {
        float: left;
        width: 104px;
        height: 44px;
        margin-top: 8px;
        margin-left: 12px;
        background-image: url("../../assets/images/home/tabDefault.png");
        background-repeat: no-repeat;
        background-size: contain;
        background-position: center;
        color: #0083cf;
        text-align: center;
        font-size: 16px;
        font-style: normal;
        font-weight: 400;
        line-height: 44px;
        cursor: pointer;
      }
      .currMenuIndex {
        color: #fff;
        font-weight: 700;
        background-image: url("../../assets/images/home/tagCurr.png");
      }
    }
    .centerUser {
      float: left;
      margin-top: 10px;
      margin-left: 10px;
    }
    .rightLang {
      float: right;
      margin-right: 15px;
      width: 68px;
      height: 28px;
      .langList {
        cursor: pointer;
        float: left;
        margin-top: 15px;
        display: flex;
        width: 34px;
        height: 28px;
        padding: 5px 8px;
        justify-content: center;
        align-items: center;
        border-top: 1px solid rgba(0, 175, 255, 0.2);
        border-right: 1px solid rgba(0, 175, 255, 0.2);
        border-bottom: 1px solid rgba(0, 175, 255, 0.2);
        background: rgba(0, 175, 255, 0.1);
        color: #98a7af;
        text-align: center;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: 22px;
      }
      .currLangIndex {
        color: #fff;
        font-weight: 700;
        border: 1px solid #00afff;
        background: rgba(0, 175, 255, 0.3);
      }
    }
  }
}
.app-main {
  height: 100%;
}
.user-dropdown {
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  padding: 8px;
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  position: relative;
}

.avatar {
  width: 28px;
  height: 28px;
  margin-right: 8px;
}

.username {
  display: inline-block;
  line-height: 18px;
  margin-right: 4px;
  font-size: 14px;
  color: #ffffff;
  width: 46px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unread-dot {
  position: absolute;
  top: 2px;
  right: 19px;
}
.el-badge__content.is-dot {
  color: red;
}

/* 自定义箭头样式 */
.custom-arrow {
  margin-left: 6px;
  transition: transform 0.2s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

/* 展开时箭头旋转 */
.custom-arrow.rotate {
  transform: rotate(180deg);
}

.notice-badge {
  margin-right: 6px;
  .el-badge {
    color: #ff0004;
  }
}

.el-dropdown__popper .el-dropdown-menu {
  overflow: hidden;
  transition: all 0.2s ease-in-out;
  width: 98px !important;
  min-width: 98px !important;
  height: 140px !important;
  border: 1px solid #003b7a !important;
  background: #050d24 !important;
  border-radius: 0 !important;
}
::v-deep .el-badge__content.is-dot {
  width: 8px !important;
  height: 8px !important;
  background-color: #ff0004 !important;
  border: none !important;
  border-radius: 50% !important;
}
</style>
